import { useCallback, useEffect, useState } from 'react';
import { Empty, Image, InfiniteScroll } from 'antd-mobile';
import moment from 'moment';
import { InbizIcon, useEvents } from '@inbiz/utils';
import { getNewsList as getNewsListData, getCounts } from '../../../service';
import { NewsProps } from '../index';
import viewIcon from '../../../icons/view.svg';
import defaultImg from '../../../icons/defaultImg.png';
import '../style.less';
import { getMessage } from '@inbiz/react';

const CardStream: React.FC<NewsProps> = (props) => {
    const { showCate, goToDetail, loadNumber, fixNewKey, standOut, everytimeLoad } = props;

    const [data, setData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const [pageIndex, setPageIndex] = useState<number>(1);

    const [configEvents] = useEvents(props.callBackEvents, props.emit)
    const getNewsList = useCallback(async (params: object) => {
        const newParams = (await configEvents.current?.onParams?.(params)) || params;
        const data = await (configEvents.current?.onRequest || getNewsListData)(newParams as any)
        return await configEvents.current?.onData?.(data) || data
    }, []);
    const getData = async (page: number) => {
        try {
            setLoading(true);
            let res: News.NewsList = await getNewsList({
                categoryId: fixNewKey?.map((item: any) => { return item.id }).toString(),
                pageIndex: page || 1,
                pageSize: everytimeLoad?.threshold,
                showNew: standOut?.isStandout,
                numNew: standOut?.threshold || undefined,
            });
            let _ids = res?.ContentList?.map((item) => item?.ID);
            let counts = await getCounts({ entitylds: _ids });
            let _data = res?.ContentList?.map((item) => {
                let _item = counts?.data?.find((item2: { EntityId: string; }) => item2?.EntityId == item?.ID);
                if (_item) {
                    return {
                        ...item,
                        View: _item?.View
                    }
                } else {
                    return item
                }
            });
            if (page == 1) {
                setData(_data);
            } else {
                setData(data?.concat(_data));
            }
            if (res?.Total > res?.PageSize * res?.PageIndex) {
                setHasMore(true);
            } else {
                setHasMore(false);
            }
            setPageIndex(res?.PageIndex);
            setLoading(false)
        } catch (error) {
            setLoading(false);
        }
    };

    const getStreamData = async () => {
        await getData(pageIndex + 1)
    }

    useEffect(() => {
        getData(1);
    }, [fixNewKey?.legnth, loadNumber, standOut]);

    return (
        <>{data?.length > 0 ? <div className="card-stream-wrapper">
            <div className="card-stream-content">
                {
                    data?.map((item) => {
                        return (
                            <div className="card-stream-item" key={item?.Id} onClick={() => { goToDetail(item) }}>
                                <Image
                                    src={item?.ImgUrl == '/inbiz/wcm/UploadFile/Plugins/TextList/Content/Images/notfound.png' ? defaultImg : item?.ImgUrl}
                                    width={184}
                                    height={104}
                                    fit='cover'
                                    style={{ borderRadius: 6 }}
                                />
                                <div className="card-stream-item-title">
                                    {showCate ? <span style={{ fontWeight: 'bold' }}>【{item?.ContentCategoryName}】</span> : null}
                                    {item?.Title}
                                </div>
                                <div className="card-stream-item-time">
                                    {moment().isSame(new Date(item?.CreateTime), 'year') ? moment(item?.CreateTime).format('MM-DD') : item?.CreateTime}
                                </div>
                                <div className="card-stream-item-creator">
                                    <div className='card-stream-item-creator-person'>
                                        <Image
                                            src={`/ImageType/GetUserAvatarById?id=${item?.CreatorID}`}
                                            width={16}
                                            height={16}
                                            fit='cover'
                                            style={{ borderRadius: 8 }}
                                        />
                                        <div>{item?.Creator}</div>
                                    </div>
                                    <div className='card-stream-item-creator-time'>
                                        <Image
                                            src={viewIcon}
                                            width={12}
                                            height={12}
                                            fit='cover'
                                        />
                                        <div>{item?.View}</div>
                                    </div>
                                </div>
                                {item?.IsNew && <div style={{ position: 'absolute', left: 0, top: -10 }}><InbizIcon type='icon-NEW' style={{ fontSize: 34 }} /></div>}
                            </div>
                        )
                    })
                }
                {
                    (!loading && data?.length)
                        ?
                        <InfiniteScroll loadMore={getStreamData} hasMore={hasMore} aria-orientation='horizontal' threshold={10} />
                        : null
                }
            </div>
        </div> : <Empty
            image={<InbizIcon type="icon-ic-zanwushuju" style={{ fontSize: '50px' }} />}
            description={getMessage('News.noData')}
        />}</>

    )
}
export default CardStream;